<template>
  <div class="app-container">
    <div class="filter-container"></div>

    <div><el-button type="primary" plain size="mini" @click="handleAdd">添加角色</el-button></div>

    <!-- 添加角色弹出层 -->
    <el-dialog :title="title" :visible.sync="dialogVisible" width="30%">
      <el-form ref="form" :model="currRole" label-width="80px" :rules="rules">
        <el-form-item label="角色名称" prop="roleName"><el-input v-model="currRole.roleName"></el-input></el-form-item>
        <el-form-item label="角色描述" prop="roleDesc"><el-input v-model="currRole.roleDesc"></el-input></el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" :loading="requesting" @click="confirmAddOrEdit">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 角色管理 -->
    <el-table :data="tableData" style="width: 100%">
      <el-table-column prop="roleName" label="部门名称/职位"></el-table-column>
      <el-table-column prop="roleDesc" label="描述"></el-table-column>
      <el-table-column prop="" label="操作">
        <template slot-scope="scope">
          <el-button @click="handleEdit(scope.row)" type="text" size="small">编辑</el-button>
          <el-button @click="handlePermission(scope.row)" type="text" size="small">编辑权限</el-button>
          <el-button @click="handleDelete(scope.row)" type="text" size="small">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--分页导航-->
    <pagination v-show="pageParams.total > 0" :total="pageParams.total" :page.sync="pageParams.pageNum" :limit.sync="pageParams.pageSize" @pagination="getList" />
  </div>
</template>

<script>
import { mapActions, mapState } from 'vuex';
export default {
  data() {
    return {
      pageParams: {
        total: 0,
        pageNum: 1,
        pageSize: 20
      },
      title: '添加角色',
      dialogVisible: false,
      requesting: false,
      tableData: [],
      currRole: {},
      rules: {
        roleName: [{ required: true, message: '请填写角色名称', trigger: 'blur' }],
        roleDesc: [{ required: true, message: '请填写角色描述', trigger: 'blur' }]
      }
    };
  },
  computed: {
    ...mapState('role', ['roleList'])
  },
  methods: {
    ...mapActions('role', ['getRoleList', 'getRoleInfo', 'getRoleResource', 'getRolePermission', 'addRole', 'updateRole', 'deleteRole']),
    fetchData() {
      this.getRoleList({
        pageNum: this.pageParams.pageNum,
        pageSize: this.pageParams.pageSize
      }).then(data => {
        this.tableData = this.roleList;
        this.pageParams.total = data.total;
      });
    },
    handleAdd() {
      this.currRole = {};
      this.dialogVisible = true;
      this.title = '添加角色';
    },
    handleEdit(data) {
      this.currRole = Object.assign({}, data);
      this.dialogVisible = true;
      this.title = '编辑角色';
    },
    getList(data) {
      this.pageParams.pageNum = data.page;
      this.pageParams.pageSize = data.limit;
      this.fetchData();
    },
    confirmAddOrEdit() {
      // 校验
      this.$refs['form'].validate(valid => {
        if (valid) {
          // 校验成功
          if (this.requesting) return;
          this.requesting = true;
          // 编辑角色信息
          if (this.currRole.id !== undefined) {
            this.updateRole({
              roleName: this.currRole.roleName,
              roleDesc: this.currRole.roleDesc,
              id: this.currRole.id
            })
              .then(res => {
                this.requesting = false;
                this.dialogVisible = false;
                this.$message({
                  type: 'success',
                  message: res.message || '更新成功'
                });
                this.fetchData();
              })
              .catch(() => {
                this.requesting = false;
              });
            return;
          }
          // 增加角色信息
          this.addRole({
            roleName: this.currRole.roleName,
            roleDesc: this.currRole.roleDesc
          })
            .then(res => {
              // 后台未返回新添加的角色ID，无法在页面中动态更新
              this.requesting = false;
              this.dialogVisible = false;
              this.fetchData()
              this.$message({
                type: 'success',
                message: res.message || '添加成功'
              });

            })
            .catch(() => {
              this.requesting = false;
            });
        } else {
          return;
        }
      });
    },
    handleInfo(data) {
      this.getRoleResource({
        id: data.id
      }).then(res => {
        this.getRolePermission({
          adminId: res.result.roleId
        });
      });
    },
    handlePermission(data) {
      this.$router.push({ path: '/sys/permission', query: { roleId: data.id } });
    },
    handleDelete(data) {
      this.$confirm(`确定删除${data.roleName}？`, '删除', {
        type: 'warning',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true;
            this.deleteRole({
              roleId: data.id
            })
              .then(res => {
                instance.confirmButtonLoading = false;


                this.$message({
                  type: 'success',
                  message: res.message || '删除成功'
                });
                this.fetchData();
                done();
              })
              .catch(() => {
                instance.confirmButtonLoading = false;
              });
          } else {
            done();
          }
        }
      });
    }
  },
  created() {
    this.fetchData();
  }
};
</script>

<style></style>
